package com.example.shop.controller;

import com.example.shop.bean.OrderBean;
import com.example.shop.bean.ProductBean;
import com.example.shop.mapper.OrderMapper;
import com.example.shop.mapper.ProductMapper;
import com.example.shop.mapper.ShoppingMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.parsing.Problem;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Controller
@RequestMapping("/order")
public class OrderController {

    @Autowired
    OrderMapper orderMapper;
    @Autowired
    ShoppingMapper shoppingMapper;
    @Autowired
    ProductMapper productMapper;
    //增加
    @ResponseBody
    @RequestMapping("/create") //创建订单
    public String createOrder(OrderBean bean){
        ProductBean productBean;
        productBean=productMapper.selectById(bean.pid);
        int pnum=productBean.num;
        //查询商品数量进行判断
        if(pnum<=0){
            return "商品已经卖光了！支付失败";
        }
        bean.ctime=new Date();
        try{
            //添加订单表，同时更新产品表中的数量
            orderMapper.insert(bean);
            shoppingMapper.shoppingInsert(bean.count,bean.pid,bean.id);
            productBean.num=pnum-1;
            productMapper.updateById(productBean);
            return "支付成功";
        }catch (Exception e){
            System.out.println(e);
            return "未知错误，支付失败！";
        }
    }
    //删除
    @ResponseBody
    @RequestMapping("/del")
    public String delOrder(Integer id){
        try{
            orderMapper.deleteById(id);
            shoppingMapper.shoppingDel(id);
            return "1";
        }catch (Exception e){
            System.out.println("删除订单失败");
            return "0";
        }
    }
    //查询用户所有订单
    @ResponseBody
    @RequestMapping("/list")
    public List<OrderBean> orderList(Integer uid){
        List<OrderBean> orderL=new ArrayList<>();
        orderL=orderMapper.orderList(uid);
        return orderL;
    }


}
